import {
  mapState
} from 'vuex'

import timCard from '@/components/commen/timCard.vue'
export default {
  data() {
    return {
      userHead: '',
      userId: '', //用户ids
      AccountType: 0, //权限
      title: '',
      //TIM变量
      nextReqMessageID: '',
      count: 15,
      isCompleted: '',
      msgList: [],
      TIM: null,

      //文字消息
      textMsg: '',
      //消息列表
      isHistoryLoading: false,
      scrollAnimation: false,
      scrollTop: 0,
      scrollToView: '',

      msgImgList: [],
      myuid: 0,
      fileCopy: [],

      //录音相关参数
      // #ifndef H5
      //H5不能录音
      RECORDER: uni.getRecorderManager(),
      // #endif
      isVoice: false,
      voiceTis: '按住 说话',
      recordTis: '手指上滑 取消发送',
      recording: false,
      willStop: false,
      initPoint: {
        identifier: 0,
        Y: 0
      },
      recordTimer: null,
      recordLength: 0,

      //播放语音相关参数
      AUDIO: uni.createInnerAudioContext(),
      playMsgid: null,
      VoiceTimer: null,
      isPlay: false,
      // 抽屉参数
      popupLayerClass: '',
      // more参数
      hideMore: true,
      //表情定义
      hideEmoji: true,
      emojiList: this.$commen.emojiList,
      //红包相关参数
      windowsState: '',
      redenvelopeData: {
        rid: null, //红包ID
        from: null,
        face: null,
        blessing: null,
        money: null
      },
      showCard: true,
      orderInfo: {}, //卡片展示的订单信息
      customMsgType: 'orderInfo', //orderInfo 订单 carSource 车源 accessory 寻配件 accessoryOrder 寻配件订单
      tab: 0, //订单类型 0买车 寻配件  1卖车 配件报价,
      module: {
        'orderInfo': 0,
        'carSource': 0,
        'accessory': 10,
        'accessoryOrder': 10,
        'carGoods': 20,
        'findCar': 30,
      },
      isAddFlow: false, //是否添加聊天记录，仅添加一次
      tabShow: '',
      statusBarHeight: 0,
    }
  },
  computed: {
    ...mapState({
      currentMessageList: state => state.news.currentMessageList,
      toUserInfo: state => state.news.toUserInfo,

    }),
    userInfo() {
      console.log('123123' + this.$store.state.timUserInfo)
      return this.$store.state.timUserInfo
      // return {
      //   img: this.$store.state.news.img,
      //   user: this.$store.state.news.user,
      //   userId: this.$store.state.news.userId,
      //   userSig: this.$store.state.news.userSig,
      // }
    },
    toUserId() {
      return this.$store.state.news.toUserId
    },
    conversationActive() {
      return this.$store.state.news.conversationActive
    },
    backFlag() {
      return this.$store.state.news.backFlag
    },
    /* footerList(){
		  let arr
		  switch (this.$store.state.user.userInfo.permious) {
		  case 'CarStore ': //4s店、汽贸店、7迈直营车
		    arr = [{
		      icon: 'iconcheliangdingdan',
		      name: '车源订单',
		      url: '/pages_order/orderAdmin/orderAdmin?type=msg'
		    },{
		      icon: 'iconjingpin',
		      name: '美护保订单',
		      url: '/pages_order/orderAdmin/orderAdmin?type=msg'
		    },{
		      icon: 'iconpeijiandingdan',
		      name: '寻配件订单',
		      url: '/pages_order/accessoryOrder/accessoryOrderList/accessoryOrderList'
		    }]
		    break
		  case 'Factory  '://车源商、主机厂
		    arr = [{
		      icon: 'iconcheliangdingdan',
		      name: '车源订单',
		      url: '/pages_order/orderAdmin/orderAdmin?type=msg'
		    }]
		    break
		  default: //养护自营+加盟门店 维保货源品牌+经销商
		    arr =  [{
		      icon: 'iconjingpin',
		      name: '美护保订单',
		      url: '/pages_order/orderAdmin/orderAdmin?type=msg'
		    },{
		      icon: 'iconpeijiandingdan',
		      name: '寻配件订单',
		      url: '/pages_order/accessoryOrder/accessoryOrderList/accessoryOrderList'
		    }	]
		    break
		  }
		  return arr
		}, */
  },
  watch: {
    currentMessageList(newVal, oldVal) {
      if (newVal.length) {
        this.msgList = newVal
      }
      this.screenMsg(newVal, oldVal)
    },
    backFlag(val) {
      if (val) {
        this.orderInfo = {
          name: this.$store.state.news.order.name,
          price: this.$store.state.news.order.price,
        }
        this.customMsgType = 'carSource'
        this.tab = this.$store.state.news.order.tab
        this.sendCustomMsg()
        this.$store.commit('news/retBackFlag')
      }
    },
  },
  components: {
    timCard
  },
  filters: {
    cutString(str, len) {
      if (str.length * 2 <= len) {
        return str
      }
      let strlen = 0
      let s = ''
      for (let i = 0; i < str.length; i++) {
        s = s + str.charAt(i)
        if (str.charCodeAt(i) > 128) {
          strlen = strlen + 2
          if (strlen >= len) {
            return s.substring(0, s.length - 1) + '...'
          }
        } else {
          strlen = strlen + 1
          if (strlen >= len) {
            return s.substring(0, s.length - 2) + '...'
          }
        }
      }
      return s
    },
  },
  onLoad(option) {
    try {
      const res = uni.getSystemInfoSync()
      //#ifndef H5
      this.statusBarHeight = res.statusBarHeight*2
      //#endif
      //#ifdef H5
      this.statusBarHeight = 44
      //#endif
    } catch (e) {
      console.log(e)
    }
    // 收到新消息
    this.tim.on(this.$TIM.EVENT.MESSAGE_RECEIVED, this.onReceiveMessage)
    this.tabShow = option.show
    this.userId = option.userId
    // 头部标题
    this.title = option.user !== 'null' ? option.user : '聊天'

    if (option.type === '1') { //从车源进入聊天
      this.orderInfo = {
        imgSrc: option.imgSrc,
        name: option.name,
        price: option.price,
        labelPrige: option.labelPrige,
        type: 'carSource',
      }
      this.customMsgType = 'carSource'
    } else if (option.type === '2') { //从订单进入聊天
      this.orderInfo = {
        name: option.name,
        price: option.price,
        type: 'orderInfo',
      }
      this.customMsgType = 'orderInfo'
      this.tab = option.tab
    } else if (option.type === '3') { //无卡片进入  发布成功
      this.showCard = false
    } else { // 4 从配件进入 5 寻配件-我的订单 6 寻车进入 7 车品进入
      this.orderInfo = this.$store.state.news.cardInfo
      this.customMsgType = this.orderInfo.type
      this.tab = option.tab //0 是询价 1 是报价
    }
    this.orderId = option.pageId
    this.TIM = this.$TIM
    this.getMsgList()
    //语音自然播放结束
    this.AUDIO.onEnded(res => {
      this.playMsgid = null
    })
    // #ifndef H5
    //录音开始事件
    this.RECORDER.onStart(e => {
      this.recordBegin(e)
    })
    //录音结束事件
    this.RECORDER.onStop(e => {
      this.recordEnd(e)
    })
    // #endif
    console.log(this.orderInfo,'orderInfo')
  },
  onShow() {
    // this.$u.debounce(this.timeOut, 500)
    // this.scrollTop = 999999999
    this.getMyInfo()
  },
  onUnload() {
    //退出页面 将所有的会话内的消息设置为已读
    let promise = this.tim.setMessageRead({
      conversationID: this.conversationActive.conversationID
    })
    promise.then(function(imResponse) {
      console.log('全部已读', imResponse)
      // 已读上报成功
    }).catch(function(imError) {
      // 已读上报失败
      console.warn('setMessageRead error:', imError)
    })
  },
  methods: {
    //删除卡片
    delCard() {
      this.showCard = false
    },
    onReceiveMessage({
      data: messageList
    }) {
      // this.handleAt(messageList);
      this.$store.commit('news/pushCurrentMessageList', messageList)
    },
    timeOut() {
      this.scrollTop = 9999999
    },
    backFn() {
      uni.navigateBack({
        delta: 1
      })
    },
    //个人信息
    async getMyInfo() {
      uni.showLoading({
        title: '加载中'
      })
      try {
        const res = await this.$api.me.getMyInfo()
        this.AccountType = res.data.account_Type
        this.userHead = res.data.headPortrait
        uni.hideLoading()
      } catch (err) {
        uni.hideLoading()
      }
    },
    clickFn(e, flag) {
      const data = JSON.parse(e)
      console.log(data,'data')
      let url
      if (data.goPage === '0') { //一成首付
        uni.navigateTo({
          url: '/pages_order/buy_order/details/details?id=' + data.id
        })
      } else if (data.goPage === '1') { //预约
        uni.navigateTo({
          url: '/pages_order/makeAppointment/makeAppointment?bookid=' + data.id
        })
      } else if (data.goPage === '2') { //询价
        uni.navigateTo({
          url: '/pages_order/carSearchDetails/carSearchDetails?id=' + data.id
        })
      } else if (data.goPage === '3') { //推广
        if (this.AccountType === 2) {
          uni.navigateTo({
            url: '/pages_order/promotionDetailsFacilitator/promotionDetailsFacilitator?id=' + data
              .id + '&userId=' + this.userId
          })
        } else {
          uni.navigateTo({
            url: '/pages_order/promotion_details/promotion_details?id=' + data.id + '&userId=' +
							this.userId
          })
        }
      } else if (data.customMsgType === 'afterSales') {
        uni.navigateTo({
          url: '/pages_order/maintenanceOrderDetail/maintenanceOrderDetail?id=' + data.id
        })
      }
    },

    //聊天的节点加上外层的div
    nodesFliter(str) {
      let nodeStr = '<div style="align-items: center;word-wrap:break-word;">' + str + '</div>'
      return nodeStr
    },
    //时间过滤
    timeFliter(timer) {
      let timeData = new Date(timer * 1000)
      let str = this.$commen.dateTimeFliter(timeData)
      return str
    },
    // 接受消息(定位消息)
    screenMsg(newVal, oldVal) {
      if (newVal.length == 0) {
        return false
      } else if (oldVal.length == 0) {
        this.$nextTick(() => {
          this.scrollToView = newVal[newVal.length - 1].ID
        })
      } else {
        if (newVal[0].ID && oldVal[0].ID) {
          if (newVal[0].ID != oldVal[0].ID && newVal.length >= this.count) {
            this.$nextTick(() => {
              this.scrollToView = oldVal[0].ID
            })
          } else {
            this.$nextTick(() => {
              this.scrollToView = newVal[newVal.length - 1].ID
            })
          }
        } else {
          this.$nextTick(() => {
            this.scrollToView = newVal[newVal.length - 1].ID
          })
        }
      }

    },
    //触发滑动到顶部(加载历史信息记录)
    loadHistory(e) {
      // 更多消息列表
      let conversationID = this.conversationActive.conversationID
      let promise = this.tim.getMessageList({
        conversationID: conversationID,
        nextReqMessageID: this.nextReqMessageID,
        count: this.count
      })
      promise.then(res => {
        if (res.data.messageList.length) {
          this.$store.commit('news/unshiftCurrentMessageList', res.data.messageList)
        }
        this.nextReqMessageID = res.data.nextReqMessageID // 用于续拉，分页续拉时需传入该字段。
        this.isCompleted = res.data.isCompleted

      })
      //这段代码很重要，不然每次加载历史数据都会跳到顶部
      this.$nextTick(function() {
        this.scrollToView = this.nextReqMessageID //跳转上次的第一行信息位置
        this.$nextTick(function() {
          this.scrollAnimation = true //恢复滚动动画
        })

      })
      this.isHistoryLoading = false
    },
    // 加载初始页面消息
    getMsgList() {
      // 历史消息列表
      let conversationID = this.conversationActive.conversationID
      let promise = this.tim.getMessageList({
        conversationID: conversationID,
        count: this.count
      })
      if (promise == undefined) {
        return false
      } else {
        promise.then(res => {
          this.$store.commit('news/pushCurrentMessageList', res.data.messageList)

          if (res.data.messageList == '' || res.data.messageList == undefined || res.data.messageList
            .length == 0) {
            return false
          } else {
            this.nextReqMessageID = res.data.nextReqMessageID // 用于续拉，分页续拉时需传入该字段。
            this.isCompleted = res.data.isCompleted
            this.$nextTick(() => {
              setTimeout(() => {
                this.scrollToView = res.data.messageList[res.data.messageList.length - 1].ID
              },1000)
            })
          }

        })
      }
      // 滚动到底部
      /* this.$nextTick(function() {

        this.scrollTop = 9999
        this.$nextTick(function() {
          this.scrollAnimation = true
        })
      }) */
    },
    //处理图片尺寸，如果不处理宽高，新进入页面加载图片时候会闪
    setPicSize(content) {
      // 让图片最长边等于设置的最大长度，短边等比例缩小，图片控件真实改变，区别于aspectFit方式。
      let maxW = uni.upx2px(350) //350是定义消息图片最大宽度
      let maxH = uni.upx2px(350) //350是定义消息图片最大高度
      if (content.w > maxW || content.h > maxH) {
        let scale = content.w / content.h
        content.w = scale > 1 ? maxW : maxH * scale
        content.h = scale > 1 ? maxW / scale : maxH
      }
      return content
    },
    //更多功能(点击+弹出)
    showMore() {
      this.isVoice = false
      this.hideEmoji = true
      if (this.hideMore) {
        this.hideMore = false
        this.openDrawer()
      } else {
        this.hideDrawer()
      }
    },
    // 打开抽屉
    openDrawer() {
      this.popupLayerClass = 'showLayer'
    },
    // 隐藏抽屉
    hideDrawer() {
      this.popupLayerClass = ''
      setTimeout(() => {
        this.hideMore = true
        this.hideEmoji = true
      }, 150)
    },
    // 选择图片发送
    chooseImage() {
      this.uploadImage('album')
    },
    //拍照发送
    camera() {
      this.uploadImage('camera')
    },
    //发红包
    handRedEnvelopes() {
      uni.navigateTo({
        url: 'HM-hand/HM-hand'
      })
      this.hideDrawer()
    },

    //发送订单详情
    sendCustomMsg() {
      const params = JSON.stringify(this.orderInfo)
      const pageParams = JSON.stringify({
        customMsgType: this.customMsgType,
        id: this.orderId,
        tab: this.tab,
        goPage: this.orderInfo.goPage, //0:一成首付2寻车列表1预约3推广
        payment: this.orderInfo.payment, //首付
        monthly: this.orderInfo.monthly //月供
      })
      let message = this.tim.createCustomMessage({
        to: this.toUserId,
        conversationType: 'C2C',
        // 消息优先级，用于群聊（v2.4.2起支持）。如果某个群的消息超过了频率限制，后台会优先下发高优先级的消息，详细请参考：https://cloud.tencent.com/document/product/269/3663#.E6.B6.88.E6.81.AF.E4.BC.98.E5.85.88.E7.BA.A7.E4.B8.8E.E9.A2.91.E7.8E.87.E6.8E.A7.E5.88.B6)
        // 支持的枚举值：TIM.TYPES.MSG_PRIORITY_HIGH, TIM.TYPES.MSG_PRIORITY_NORMAL（默认）, TIM.TYPES.MSG_PRIORITY_LOW, TIM.TYPES.MSG_PRIORITY_LOWEST
        // priority: TIM.TYPES.MSG_PRIORITY_HIGH,
        payload: {
          data: 'orderInfo', // 用于标识该消息类型
          description: params, // 用于聊天记录信息展示
          extension: pageParams, //用于点击聊天记录跳转详情
        }
      })
      this.$store.commit('news/pushCurrentMessageList', message)
      let pomise = this.tim.sendMessage(message)
      this.scrollAnimation = true
      pomise.then(res => {
        this.$nextTick(() => {
          // 滚动到底
          this.scrollToView = res.data.message.ID
          this.showCard = false
        })
      }).catch(err => {
        console.log(err + '111')
      })
      if (!this.isAddFlow) {
        this.addChatFlow()
      }
    },

    // 选择表情
    chooseEmoji() {
      this.hideMore = true
      if (this.hideEmoji) {
        this.hideEmoji = false
        this.openDrawer()
      } else {
        this.hideDrawer()
      }
    },
    //添加表情
    addEmoji(em) {
      this.textMsg += em.alt
    },

    //获取焦点，如果不是选表情ing,则关闭抽屉
    textareaFocus() {
      if (this.popupLayerClass == 'showLayer' && this.hideMore == false) {
        this.hideDrawer()
      }
    },
    // 发送文字消息
    sendText() {
      this.hideDrawer() //隐藏抽屉
      if (!this.textMsg) {
        return
      }
      let content = this.replaceEmoji(this.textMsg)
      let msg = {
        text: content
      }
      this.sendMsg(msg, 'text')
      this.textMsg = '' //清空输入框
    },
    //替换表情符号为图片
    replaceEmoji(str) {
      let replacedStr = str.replace(/\[([^(\]|\[)]*)\]/g, (item, index) => {
        for (let i = 0; i < this.emojiList.length; i++) {
          let row = this.emojiList[i]
          for (let j = 0; j < row.length; j++) {
            let EM = row[j]
            if (EM.alt == item) {
              //在线表情路径，图文混排必须使用网络路径，请上传一份表情到你的服务器后再替换此路径
              //比如你上传服务器后，你的100.gif路径为https://www.xxx.com/emoji/100.gif 则替换onlinePath填写为https://www.xxx.com/emoji/
              let onlinePath = 'https://files.yzsheng.com/client/emoji/'
              let imgstr = '<img src="' + EM.url + '">'
              return imgstr
            }
          }
        }
      })
      return replacedStr
    },

    // 发送文本消息
    sendMsg(content, type) {
      let message = this.tim.createTextMessage({
        to: this.toUserId,
        conversationType: 'C2C',
        payload: {
          text: content.text
        }
      })
      this.$store.commit('news/pushCurrentMessageList', message)
      let pomise = this.tim.sendMessage(message)
      this.scrollAnimation = true
      pomise.then(res => {
        this.$nextTick(() => {
          // 滚动到底
          this.scrollToView = res.data.message.ID
        })
      }).catch(err => {
        console.log(err)

      })

      if (!this.isAddFlow) {
        this.addChatFlow()
      }
    },

    //发送语音消息
    sendRecord(content) {
      let message = this.tim.createCustomMessage({
        to: this.toUserId,
        conversationType: 'C2C',
        // 消息优先级，用于群聊（v2.4.2起支持）。如果某个群的消息超过了频率限制，后台会优先下发高优先级的消息，详细请参考：https://cloud.tencent.com/document/product/269/3663#.E6.B6.88.E6.81.AF.E4.BC.98.E5.85.88.E7.BA.A7.E4.B8.8E.E9.A2.91.E7.8E.87.E6.8E.A7.E5.88.B6)
        // 支持的枚举值：TIM.TYPES.MSG_PRIORITY_HIGH, TIM.TYPES.MSG_PRIORITY_NORMAL（默认）, TIM.TYPES.MSG_PRIORITY_LOW, TIM.TYPES.MSG_PRIORITY_LOWEST
        // priority: TIM.TYPES.MSG_PRIORITY_HIGH,
        payload: {
          data: 'record', // 用于标识该消息类型
          description: content.url, // 用于装载url
          extension: content.times, //录音时长
        }
      })
      this.$store.commit('news/pushCurrentMessageList', message)
      let pomise = this.tim.sendMessage(message)
      this.scrollAnimation = true
      pomise.then(res => {
        this.$nextTick(() => {
          // 滚动到底
          this.scrollToView = res.data.message.ID
        })
      }).catch(err => {
        console.log(err + '111')
        if (err.code === 20003) {
          uni.showToast({
            title: '对方暂无账号，无法发送信息',
            icon: 'none',
          })
        } else {
          uni.showToast({
            title: '发送失败，请稍后重试',
            icon: 'none',
          })
        }

      })
    },

    // 添加文字消息到列表
    addTextMsg(msg) {
      this.msgList.push(msg)
    },
    // 添加语音消息到列表
    addVoiceMsg(msg) {
      this.msgList.push(msg)
    },
    // 添加图片消息到列表
    // addImgMsg(msg) {
    //   msg.msg.content = this.setPicSize(msg.msg.content)
    //   this.msgImgList.push(msg.msg.content.url)
    //   this.msgList.push(msg)
    // },
    addRedEnvelopeMsg(msg) {
      this.msgList.push(msg)
    },
    // 添加系统文字消息到列表
    addSystemTextMsg(msg) {
      this.msgList.push(msg)
    },
    // 添加系统红包消息到列表
    addSystemRedEnvelopeMsg(msg) {
      this.msgList.push(msg)
    },
    // 打开红包
    openRedEnvelope(msg, index) {
      let rid = msg.content.rid
      uni.showLoading({
        title: '加载中...'
      })
      //模拟请求服务器效果
      setTimeout(() => {
        //加载数据
        if (rid == 0) {
          this.redenvelopeData = {
            rid: 0, //红包ID
            from: '大黑哥',
            face: '/static/img/im/face/face.jpg',
            blessing: '恭喜发财，大吉大利',
            money: '已领完'
          }
        } else {
          this.redenvelopeData = {
            rid: 1, //红包ID
            from: '售后客服008',
            face: '/static/img/im/face/face_2.jpg',
            blessing: '恭喜发财',
            money: '0.01'
          }
          if (!msg.content.isReceived) {
            // {type:"system",msg:{id:8,type:"redEnvelope",content:{text:"你领取了售后客服008的红包"}}},
            this.sendSystemMsg({
              text: '你领取了' + (msg.userinfo.uid == this.myuid ? '自己' : msg.userinfo
                .username) + '的红包'
            }, 'redEnvelope')
            this.msgList[index].msg.content.isReceived = true
          }
        }
        uni.hideLoading()
        this.windowsState = 'show'

      }, 200)
    },

    // 关闭红包弹窗
    closeRedEnvelope() {
      this.windowsState = 'hide'
      setTimeout(() => {
        this.windowsState = ''
      }, 200)
    },
    sendSystemMsg(content, type) {
      let lastid = this.msgList[this.msgList.length - 1].msg.id
      lastid++
      let row = {
        type: 'system',
        msg: {
          id: lastid,
          type: type,
          content: content
        }
      }
      this.screenMsg(row)
    },
    //领取详情
    toDetails(rid) {
      uni.navigateTo({
        url: 'HM-details/HM-details?rid=' + rid
      })
    },
    // 预览图片
    // showPic(msg) {
    //   uni.previewImage({
    //     indicator: 'none',
    //     current: msg.content.url,
    //     urls: this.msgImgList
    //   })
    // },
    // 播放语音
    playVoice(msg, id) {
      if (!this.isPlay) {
        this.playMsgid = id
        console.log('语音地址：', msg)
        this.AUDIO.src = msg
        this.isPlay = true
        this.$nextTick(function() {
          this.AUDIO.play()
        })
      } else {
        this.isPlay = false
        this.$nextTick(function() {
          this.AUDIO.stop()
        })
      }
    },
    // 录音开始
    voiceBegin(e) {
      if (e.touches.length > 1) {
        return
      }
      this.initPoint.Y = e.touches[0].clientY
      this.initPoint.identifier = e.touches[0].identifier
      this.RECORDER.start({
        format: 'mp3'
      }) //录音开始,
    },
    //录音开始UI效果
    recordBegin(e) {
      this.recording = true
      this.voiceTis = '松开 结束'
      this.recordLength = 0
      this.recordTimer = setInterval(() => {
        this.recordLength++
      }, 1000)
    },
    // 录音被打断
    voiceCancel() {
      this.recording = false
      this.voiceTis = '按住 说话'
      this.recordTis = '手指上滑 取消发送'
      this.willStop = true //不发送录音
      this.RECORDER.stop() //录音结束
    },
    // 录音中(判断是否触发上滑取消发送)
    voiceIng(e) {
      if (!this.recording) {
        return
      }
      let touche = e.touches[0]
      //上滑一个导航栏的高度触发上滑取消发送
      if (this.initPoint.Y - touche.clientY >= uni.upx2px(100)) {
        this.willStop = true
        this.recordTis = '松开手指 取消发送'
      } else {
        this.willStop = false
        this.recordTis = '手指上滑 取消发送'
      }
    },
    // 结束录音
    voiceEnd(e) {
      if (!this.recording) {
        return
      }
      this.recording = false
      this.voiceTis = '按住 说话'
      this.recordTis = '手指上滑 取消发送'
      this.RECORDER.stop() //录音结束
    },
    //录音结束(回调文件)
    recordEnd(e) {
      clearInterval(this.recordTimer)
      if (!this.willStop) {
        // let msg = {
        //   length: 0,
        //   url: e.tempFilePath
        // }
        // let min = parseInt(this.recordLength / 60)
        // let sec = this.recordLength % 60
        // min = min < 10 ? '0' + min : min
        // sec = sec < 10 ? '0' + sec : sec
        // msg.length = min + ':' + sec
        if (this.recordLength < 2) {
          uni.showToast({
            title: '说话时间太短',
            icon: 'none',
          })
          return
        }
        const _this = this
        this.getFileConfig(params => {
          console.log('文件上传地址： ', params)
          uni.uploadFile({
            url: params.host,
            formData: {
              policy: params.policy,
              authorization: params.auth
            },
            filePath: e.tempFilePath,
            name: 'file',
            success(res) {
              console.log('上传文件返回： ', res)
              const resObj = JSON.parse(res.data)
              _this.sendRecord({
                url: 'https://ztc.yzsheng.com' + resObj.url,
                times: _this.recordLength + ''
              })
            },
          })
        })
      } else {
        console.log('取消发送录音')
      }
      this.willStop = false
    },
    // 切换语音/文字输入
    switchVoice() {
      this.hideDrawer()
      this.isVoice = this.isVoice ? false : true
    },

    discard() {
      return
    },

    //选取图片
    uploadImage(type) {
      this.hideDrawer()
      const _this = this
      uni.chooseImage({
        count: 1, // 默认9
        sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
        sourceType: ['type'], // 从相册选择
        success(result) {
          _this.getImageConfig(params => {
            uni.uploadFile({
              url: params.host,
              formData: {
                policy: params.policy,
                authorization: params.auth
              },
              filePath: result.tempFilePaths[0],
              name: 'file',
              success(res) {
                const resObj = JSON.parse(res.data)
                _this.sendImg('https://files.yzsheng.com' + resObj.url)
              },
            })
          })
        }
      })
    },

    sendImg(content) {
      console.log(content)
      let message = this.tim.createCustomMessage({
        to: this.toUserId,
        conversationType: 'C2C',
        // 消息优先级，用于群聊（v2.4.2起支持）。如果某个群的消息超过了频率限制，后台会优先下发高优先级的消息，详细请参考：https://cloud.tencent.com/document/product/269/3663#.E6.B6.88.E6.81.AF.E4.BC.98.E5.85.88.E7.BA.A7.E4.B8.8E.E9.A2.91.E7.8E.87.E6.8E.A7.E5.88.B6)
        // 支持的枚举值：TIM.TYPES.MSG_PRIORITY_HIGH, TIM.TYPES.MSG_PRIORITY_NORMAL（默认）, TIM.TYPES.MSG_PRIORITY_LOW, TIM.TYPES.MSG_PRIORITY_LOWEST
        // priority: TIM.TYPES.MSG_PRIORITY_HIGH,
        payload: {
          data: 'chatFile', // 用于标识该消息类型
          description: content, // 用于装载url
          extension: ''
        }
      })
      this.$store.commit('news/pushCurrentMessageList', message)
      let pomise = this.tim.sendMessage(message)
      pomise.then(res => {
        this.scrollAnimation = true
        this.$nextTick(() => {
          // 滚动到底
          this.scrollToView = res.data.message.ID
        })
      }).catch(err => {
        console.log(err + '111')
        if (err.code === 20003) {
          uni.showToast({
            title: '对方暂无账号，无法发送信息',
            icon: 'none',
          })
        } else {
          uni.showToast({
            title: '发送失败，请稍后重试',
            icon: 'none',
          })
        }

      })

      this.hideDrawer()

      if (!this.isAddFlow) {
        this.addChatFlow()
      }
    },

    //获取图片上传配置信息
    async getImageConfig(callback) {
      try {
        const res = await this.$api.user.getImageConfig()
        callback(res.data)
      } catch (e) {
        //TODO handle the exception
      }
    },

    //获取文件上传配置信息
    async getFileConfig(callback) {
      try {
        const res = await this.$api.user.getFileConfig({
          Suffix: 'mp3'
        })
        callback(res.data)
      } catch (e) {
        console.log(e)
        //TODO handle the exception
      }
    },

    //图片预览
    previewImage(url) {
      uni.previewImage({
        current: 0,
        urls: [url],
      })
    },

    //跳转商品/订单页
    gotoOrder() {
      console.log(844)
    },

    //跳转订单列表
    gotoOrderList(i) {
      this.showCard = false
      uni.navigateTo({
        url: this.footerList[i].url
      })
    },

    //进店、
    gotoStore() {
      uni.navigateTo({
        url: '/pages_store/newCarStore/index/index?storeid=' + this.toUserId
      })
    },

    //添加聊天日志
    addChatFlow() {
      // this.$api.news.addChatFlow({
      //   channel: 0,
      //   module: this.module[this.customMsgType],
      //   active_Store_Id: this.userInfo.userId,
      //   active_User_Id: this.$store.state.tid,
      //   passive_Store_Id: this.toUserId,
      //   passive_User_Id: '',
      // }).then(res => {
      //   console.log(res)
      //   this.isAddFlow = true
      // }).catch(e => {
      //   console.log(e)
      // })
    }
  }
}
